// @ts-nocheck
import { defineStore } from 'pinia';
import {axios_request} from "@/api/milliaAxios";


export const useUserStore = defineStore('user', {
    state: () => ({
        access_token: '',
        csrf_token: '',
        isAuthenticated: false,
        UID:'',
        userData: {},  // 存储用户基本数据
        ctfWebData: [],  // 存储Web题目数据
        ctfCryptoData: [],  // 存储Crypto题目数据
        ctfPwnData: [],  // 存储Pwn题目数据
        ctfMiscData: [],  // 存储Misc题目数据
    }),
    getters: {
        isLoggedIn: (state) => state.isAuthenticated,
    },
    actions: {
        // 用户登录函数
        async login(access_token: string, csrf_token: string, user_id: string) {
            this.isAuthenticated = true;
            this.access_token = access_token;
            this.csrf_token = csrf_token;
            localStorage.setItem('authToken', access_token);
            localStorage.setItem('csrfToken', csrf_token);
            this.UID = user_id;

            const keys = ['username', 'email', 'telephone'];
            const newUserData = await this.fetchUserInfo(keys, this.UID);
            this.updateUserData(newUserData);

            console.log('登录后获取到的数据：', this.userData);
        },
        // 用户注销函数
        logout() {
            // 清除用户认证状态和令牌
            this.isAuthenticated = false;
            this.access_token = '';
            this.csrf_token = '';
            this.UID = '';
            // 清除本地存储中的令牌
            localStorage.removeItem('authToken');
            localStorage.removeItem('csrfToken');
            // 清空用户数据
            Object.keys(this.userData).forEach(key => {
                delete this.userData[key];
            });
            this.userData = {};
        },
        // 获取用户基本信息的函数请求
        async fetchUserInfo(keys, UID: string) {
            // 获取要从数据库得到的数据, keys ['username', 'email']
            const data = {
                "keys": keys,
                "user_id": UID
            }
            const res = await axios_request('/api/user/fetch_userinfo/', JSON.stringify(data),'post')
            if (res.status == 200) {
                console.log(res.data.msg)
                return res.data.user_data

            }else if (res.status == 202) {
                return res.data.msg
            }
        },
        // 刷新用户信息的函数，配合fetchUserInfo使用
        updateUserData(newData) {
            // 更新userData对象
            for (const key in newData) {
                console.log(key)
                if (Object.hasOwnProperty.call(newData, key)) {
                    console.log(`数据${Object.hasOwnProperty.call(this.userData, key) ? '更新' : '添加'}后:`)
                    this.userData[key] = newData[key];
                    console.log(this.userData);
                }
            }
        },
        // 获取Web题库信息
        async fetchWebInfo(){
            const res = await axios_request('/api/CTF/fetch_web_info/',{},'get')
            if (res.status == 200) {
                console.log('成功获取题目数据：' + res.data.msg)
                console.log(res.data.question_info)

                // 存储数据到ctfWebData
                this.ctfWebData = res.data.question_info;

                return res.data.question_info

            }else if (res.status == 202) {
                return res.data.msg
            }
        }
    },
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: localStorage,
            },
        ],
    },
});
